package com.ctcemti.mdm.project.sys.service.impl;

import com.ctcemti.mdm.common.result.Result;
import com.ctcemti.mdm.common.result.ResultEnum;
import com.ctcemti.mdm.common.result.ResultUtil;
import com.ctcemti.mdm.common.util.StringUtils;
import com.ctcemti.mdm.project.sys.dao.ResPersonMapper;
import com.ctcemti.mdm.project.sys.entity.ResPerson;
import com.ctcemti.mdm.project.sys.service.IResPersonService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.UUID;

@Service
public class ResPersonServiceImpl implements IResPersonService {

    @Autowired
    ResPersonMapper resPersonMapper;


    @Override
    public Result insertOrUpdate(ResPerson resPerson) {
        if(resPerson == null){
            return ResultUtil.error(ResultEnum.ZTSJ_1001);
        }
        //判断身份证
        if(!StringUtils.isNullOrEmpty(resPerson.getIdCard())){
            ResPerson param = new ResPerson();
            param.setCompanyId(resPerson.getCompanyId());
            param.setIdCard(resPerson.getIdCard());
            List<ResPerson> testResLabour = resPersonMapper.select(param);
            if(testResLabour != null){
                if(testResLabour.size() == 1){
                    if(!testResLabour.get(0).getId().equals(resPerson.getId())){
                        return ResultUtil.error(ResultEnum.ZTSJ_1005);
                    }
                }
                if(testResLabour.size() > 1){
                    return ResultUtil.error(ResultEnum.ZTSJ_1005);
                }
            }
        }else{
            return ResultUtil.error(ResultEnum.ZTSJ_1001);
        }

        if(resPerson.getId() == null || resPerson.getId().equals("")){
            resPerson.setId(UUID.randomUUID().toString());
            resPersonMapper.insert(resPerson);
        }else{
            resPersonMapper.updateByPrimaryKeySelective(resPerson);
        }
        return ResultUtil.success();
    }

    @Override
    public Result delete(ResPerson resPerson) {
        if(resPerson == null){
            return ResultUtil.error(ResultEnum.ZTSJ_1001);
        }
        resPersonMapper.delete(resPerson);
        return ResultUtil.success();
    }

    @Override
    public PageInfo<ResPerson> getResPerson(ResPerson resPerson, Integer page, Integer limit) {
        PageHelper.startPage(page,limit);
        PageHelper.orderBy("id");
        List<ResPerson> resLabourCompanies = resPersonMapper.select(resPerson);
        PageInfo<ResPerson> pageInfo = new PageInfo<>(resLabourCompanies);
        return pageInfo;
    }

    @Override
    public List<ResPerson> selectResPersonCompany(ResPerson entity) {
        return resPersonMapper.select(entity);
    }
}
